package org.magicbox.qjunTPO.controller;

import org.magicbox.qjunTPO.common.lang.Result;
import org.magicbox.qjunTPO.entity.Supuser;
import org.magicbox.qjunTPO.entity.User;
import org.magicbox.qjunTPO.service.SupuserService;
import org.magicbox.qjunTPO.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;

@Controller
public class LoginController {
    @Autowired
    UserService userService;

    @Autowired
    SupuserService supuserService;
    @ResponseBody
    @RequestMapping("/toLogin")
    public Result error(){
        return Result.fail(499,"请您登录!");
    }

    @ResponseBody
    @RequestMapping("/toSuccess")
    public Result toSuccess(){
        Integer uid;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication instanceof AnonymousAuthenticationToken)) {
            uid =new Integer(authentication.getName()) ;
            if(authentication.getName().length()!=4){
                User byId = userService.getById(uid);
                byId.setLastDate(LocalDateTime.now());
                userService.updateById(byId);
                return Result.success(byId);
            }else {
                Supuser byId = supuserService.getById(uid);
                return Result.success(byId);
            }
        }
        return Result.fail(499,"失败了,请重新登录！");
    }

    @ResponseBody
    @RequestMapping("/toFailure")
    public Result toFailure(){
        return Result.fail(499,"账号或者密码错误!");
    }

}
